<!-- 页面说明 -->
<template>
  <main>

    <div class="width">
      <a-row class="width">
        <a-col :span="6">
          <a-checkbox v-model:checked="checkedMenu" @change="handleMenuChanged"
                      :value="menu.menuId"><span
              class="menuTitle">{{ menu.menuName }}</span></a-checkbox>
        </a-col>
        <a-col :span="18">
          <a-row>
            <a-checkbox-group v-model:value="buttonChecked" class="width">
              <a-col class="margin-bottom-10" :span="8" v-for="button in menu.buttonList">
                <a-checkbox @change="handleButtonChanged" :value="button.id">{{ button.name }}</a-checkbox>
              </a-col>
            </a-checkbox-group>
          </a-row>
        </a-col>
      </a-row>
      <div class="line margin-bottom-10"></div>
    </div>
  </main>
</template>
<script lang="ts">
export default {
  props: {
    menu: {type: Object},
    rightIds: {type: Array}
  },
  components: {},
  data() {
    return {
      //按钮选择项
      buttonChecked: [],
      //是否选择了菜单
      checkedMenu: false,
      //按钮全选的选项
      allButtonChecked: [],
      version: 0,
      //选择的按钮列表
      list: []
    }
  },
  methods: {
    handleMenuChanged(e) {
      this.buttonChecked = e.target.checked ? this.allButtonChecked : [];
      this.version++;
    },
    handleButtonChanged() {
      this.version++;
    }
  },
  computed: {

  },

  watch: {
    version() {
      if (this.buttonChecked.length > 0 && !this.checkedMenu) {
        this.checkedMenu = true;
      }

      this.list = [];
      if (this.checkedMenu) {
        this.list.push(this.$props.menu.menuId);
        for (let id of this.buttonChecked) {
          this.list.push(id);
        }
      }
      this.$emit("changed", this.$props.menu.menuGroupName + "-" + this.$props.menu.menuId, this.list);
    }
  },
  mounted() {
    let map = new Map();
    let hasValue = false;
    //把权限ID转换成Map
    for (let id of this.$props.rightIds) {
      map.set(id,id);
    }
    //取出菜单
    let menu = this.$props.menu;
    if(map.has(menu.menuId)){
      //如果权限中包含菜单，将菜单勾选，同时菜单ID添加到列表中
      hasValue = true;
      this.checkedMenu = true;
      this.list.push(menu.menuId);
    }
    this.allButtonChecked = [];
    if (menu.buttonList) {
      for (let button of menu.buttonList) {
        if(map.has(button.id)){
          //将权限中包含的菜单勾选
          hasValue = true;
          this.list.push(button.id);
          this.buttonChecked.push(button.id);
        }
        this.allButtonChecked.push(button.id);
      }
    }
    if(hasValue){
      //如果菜单或者按钮又被选中，回调父级
      this.$emit("changed", this.$props.menu.menuGroupName + "-" + this.$props.menu.menuId, this.list);
    }
  }
}
</script>
<style scoped>
.menuTitle {
  font-weight: bold;
}

.groupTitle {
  font-size: 2rem;
}
</style>